You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
In [1]:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
In [63]:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
1、对象引用的复制,必须引用同一个对象,才能保证当前引用的对象
2、考虑进位以及低位数加高位数的情况
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ans = p = ListNode(0)
carry = 0
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, p.val = divmod(v1 + v2 + carry, 10)
if l1 or l2 or carry:
p.next = ListNode(0)
p = p.next
return ans
In [60]:
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
In [61]:
l = Solution().addTwoNumbers(l1, l2)
In [62]:
while l:
print (l.val)
l = l.next
In [ ]: